import http from './request'
import { showToast } from './request'

class ApiService {
  constructor() {
    // 单例模式实现
    if (ApiService.instance) {
      return ApiService.instance
    }

    this.appKey = '9101fca7a5471bb6'
    this.sign =
      'OTU0Y2M5NzIwNzgwYzM4OGMwMjk1Nzc2NmIwZjUzZjk4NzEyNTFlYjg3YzA3MjIzNWVhZjEwMzJlYTE2Zjc5Zg=='

    // 预制的常用请求参数
    this.baseParams = {
      appKey: this.appKey,
      sign: this.sign,
    }

    // 工作流Hook配置
    this.workflowHooks = {
      PROJECT_SUBMIT: 'NjhhNjk3MDhlYTA3YWMyZGEwZTZjZmIz', // 项目提交
      PROJECT_EDIT: 'NjhiMTc3OTQ4MjMxNGY3M2U5MTA1YWZl', // 项目编辑
      SELECT_DATA: 'NjhhODM3ZTE3NDNhMzExY2E0OWZlMmI5', // 选择数据
      REGISTER: 'NjhhZTZiNDZiZTg1NDMyZmY0NmQ0OTll',
      DEMAND: 'NjhhZWI5MTFiZTg1NDMyZmY0NzA0NzVk',
      DELETE: 'NjhhZWQwMmJiZTg1NDMyZmY0NzE3Y2E0',
      CUSTOMER: 'NjhhZWZmODNiZTg1NDMyZmY0NzFkZDcz',
      CUSTOMERROLE: 'NjhhZjA5MjhiZTg1NDMyZmY0NzFlOTY4',
      ROLERECORD: 'NjhiMDA2OWEyNGMzNjExM2I3M2IwNDYy',
      QUOTATION_DETAILS: 'NjhiMDYyNWEyNGMzNjExM2I3M2M0ZDQz',
      ROLES: 'NjhiMDZkOWQyNGMzNjExM2I3M2M2MzNi',
      YBB: 'NjhiMDMzMjcyNGMzNjExM2I3M2MwNGMy',
      DEMANDLIST: 'NjhiMTMwNTI4MjMxNGY3M2U5MGYwNjNl',
    }

    ApiService.instance = this
  }

  // 工作表ID枚举定义
  static WORKSHEETENUM = {
    PROJECTS: '6876257b872d9db2c7ba529a',
    DEMAND: '6876257b872d9db2c7ba5292',
    CANDIDATE: '6876257b872d9db2c7ba5297',
    CLUSTER: '6876257b872d9db2c7ba5290',
    USER: '68a7d27a0372283d1e9247d2',
  }

  // "filters":[
  //   {
  //           "controlId":"686df6df33681903aca1068e",
  //           "dataType":2,
  //           "spliceType":1,
  //           "filterType":2,
  //           "value":"61"
  //       }
  //  ]

  /**
   * 获取筛选行数据 - 优化版本
   * @param {string} worksheetId - 工作表ID
   * @param {boolean} notGetTotal - 是否不获取总数
   * @param {Array} filters - 筛选条件
   * @returns {Promise} 返回数据Promise
   */
  async getFilterRows({
    worksheetId,
    pageIndex = 1,
    pageSize = 20,
    notGetTotal = true,
    filters = [],
    useCache = true, // 新增：是否使用缓存
  } = {}) {
    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: worksheetId,
        viewId: '',
        pageIndex: pageIndex,
        pageSize: pageSize,
        notGetTotal: notGetTotal,
        filters: filters,
      }

      // 对于首页数据，使用较短的超时时间
      const options = {
        timeout: pageIndex === 1 ? 8000 : 10000,
      }

      const res = await http.post('/getFilterRows', requestData, options)
      return res
    } catch (error) {
      console.error('获取筛选行数据失败:', error)

      // 提供更友好的错误提示
      const errorMessage = this.getErrorMessage(error)
      showToast(errorMessage)

      throw error
    }
  }

  async register({ worksheetId, controls, triggerWorkflow = false } = {}) {
    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: worksheetId,
        controls: controls,
        triggerWorkflow: triggerWorkflow,
      }

      const res = await http.post('/addRow', requestData, {
        timeout: 6000, // 单行数据使用更短超时
      })
      return res
    } catch (error) {
      console.error('【register】注册失败，错误详情:', {
        message: error.message,
        stack: error.stack,
        error: error,
      })

      throw error
    }
  }

  /**
   * 根据ID获取行数据 - 优化版本
   * @param {string} rowId - 行ID
   * @param {string} worksheetId - 工作表ID
   * @param {boolean} getSystemControl - 是否获取系统控件
   * @returns {Promise} 返回数据Promise
   */
  async getRowById({ rowId, worksheetId, getSystemControl = false } = {}) {
    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: worksheetId,
        rowId: rowId,
        getSystemControl: getSystemControl,
      }

      const res = await http.post('/getRowByIdPost', requestData, {
        timeout: 6000, // 单行数据获取使用更短超时
      })
      return res
    } catch (error) {
      console.error('根据ID获取行数据失败:', error)

      const errorMessage = this.getErrorMessage(error)
      showToast(errorMessage)

      throw error
    }
  }

  /**
   * 批量预加载数据
   * @param {Array} requests - 请求配置数组
   */
  async preloadData(requests = []) {
    const preloadPromises = requests.map((config) => {
      if (config.type === 'getFilterRows') {
        return http.preload(
          '/getFilterRows',
          {
            ...this.baseParams,
            ...config.params,
          },
          'POST',
        )
      } else if (config.type === 'getRowById') {
        return http.preload(
          '/getRowByIdPost',
          {
            ...this.baseParams,
            ...config.params,
          },
          'POST',
        )
      }
    })

    try {
      await Promise.allSettled(preloadPromises)
      console.log('数据预加载完成')
    } catch (error) {
      console.log('预加载失败，但不影响正常使用:', error)
    }
  }

  /**
   * 快速获取候选人数据（带优化）
   */
  async getCandidatesQuick(options = {}) {
    const defaultOptions = {
      worksheetId: ApiService.WORKSHEETENUM.CANDIDATE,
      pageIndex: 1,
      pageSize: 10, // 首次加载较少数据，提高速度
      notGetTotal: false,
      ...options,
    }

    return this.getFilterRows(defaultOptions)
  }

  /**
   * 快速获取项目数据（带优化）
   */
  async getProjectsQuick(options = {}) {
    const defaultOptions = {
      worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
      pageIndex: 1,
      pageSize: 10,
      notGetTotal: false,
      ...options,
    }

    return this.getFilterRows(defaultOptions)
  }

  /**
   * 获取友好的错误信息
   * @param {Error} error - 错误对象
   * @returns {string} 友好的错误信息
   */
  getErrorMessage(error) {
    if (error.message?.includes('timeout')) {
      return '网络超时，请检查网络连接'
    } else if (error.message?.includes('Network Error')) {
      return '网络连接失败，请重试'
    } else if (error.message?.includes('401')) {
      return '登录已过期，请重新登录'
    } else if (error.message?.includes('500')) {
      return '服务器异常，请稍后重试'
    } else {
      return error.message || '请求失败，请重试'
    }
  }

  /**
   * 清除相关缓存
   * @param {string} worksheetId - 工作表ID
   */
  clearWorksheetCache(worksheetId) {
    http.clearCache(worksheetId)
  }

  /**
   * 清除所有API缓存
   */
  clearAllCache() {
    http.clearCache()
  }

  async getRoles(data) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.ROLES}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('获取角色失败:', error)
      throw error
    }
  }

  async getDemandList(data) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.DEMANDLIST}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('获取角色失败:', error)
      throw error
    }
  }

  async getRoleRecord(data) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.ROLERECORD}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('getRoleRecord失败:', error)
      throw error
    }
  }

  async getRoleStatus(data) {
    try {
      const hookUrl = `/api/workflow/hooks/NjhiN2YxZDdkZGE0MTI2NGYwZjMzNGY4`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      const result = await response.json()
      return result
    } catch (error) {
      console.error('查询角色需求明细失败:', error)
      throw error
    }
  }

  async getRoleList(data) {
    try {
      const hookUrl = `/api/workflow/hooks/NjhiODIwMjBkZGE0MTI2NGYwZjRhNTRi`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      const result = await response.json()
      return result
    } catch (error) {
      console.error('查询角色需求明细失败:', error)
      throw error
    }
  }

  async getDemand(demanddata) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.DEMAND}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(demanddata),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      const result = await response.json()
      return result
    } catch (error) {
      console.error('查询角色需求明细失败:', error)
      throw error
    }
  }

  async registerUser(registerdata) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.REGISTER}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(registerdata),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      console.log('注册成功')
      console.log('注册结果:', result)
      return result
    } catch (error) {
      console.error('注册用户失败:', error)
      throw error
    }
  }

  async getCustomer(data) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.CUSTOMER}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('getCustomer失败:', error)
      throw error
    }
  }

  async getQuotationDetails(data) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.QUOTATION_DETAILS}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('获取报价明细失败:', error)
      throw error
    }
  }

  async getYbb(data) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.YBB}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('失败:', error)
      throw error
    }
  }

  async selectRole(roleData) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.CUSTOMERROLE}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(roleData),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      console.log('选择角色成功')
      console.log('选择角色结果:', result)
      return result
    } catch (error) {
      console.error('选择角色失败:', error)
      throw error
    }
  }

  async deleteRow(deleteData) {
    try {
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.DELETE}`
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(deleteData),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      console.log('注册成功')
      console.log('注册结果:', result)
      return result
    } catch (error) {
      console.error('注册用户失败:', error)
      throw error
    }
  }

  async selectReferrer(selectData) {
    try {
      // 构建完整的hook地址
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.SELECT_DATA}`

      // 对于工作流hook，我们需要使用不同的baseURL，直接使用fetch避免baseURL冲突
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(selectData),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('选择推荐人失败:', error)
      throw error
    }
  }

  /**
   * 提交项目信息到工作流hook
   * @param {Object} projectData - 项目数据
   * @param {string} hookId - hook ID，默认为项目提交的hook ID
   * @returns {Promise} 返回提交结果
   */
  async submitProject(projectData) {
    try {
      // 构建完整的hook地址
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.PROJECT_SUBMIT}`

      // 对于工作流hook，我们需要使用不同的baseURL，直接使用fetch避免baseURL冲突
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(projectData),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('提交项目失败:', error)
      throw error
    }
  }

  async editProject(projectData) {
    try {
      // 构建完整的hook地址
      const hookUrl = `/api/workflow/hooks/${this.workflowHooks.PROJECT_EDIT}`

      // 对于工作流hook，我们需要使用不同的baseURL，直接使用fetch避免baseURL冲突
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(projectData),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('提交项目失败:', error)
      throw error
    }
  }

  /**
   * 通用的工作流hook提交方法
   * @param {string} hookId - hook ID
   * @param {Object} data - 要提交的数据
   * @returns {Promise} 返回提交结果
   */
  async submitWebhook(hook, data) {
    try {
      // 构建完整的hook地址
      const hookUrl = `/api/workflow/hooks/${hook}`

      // 对于工作流hook，我们需要使用不同的baseURL，直接使用fetch避免baseURL冲突
      const response = await fetch(hookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      return result
    } catch (error) {
      console.error('提交项目失败:', error)
      throw error
    }
  }
}

// 创建并导出单例实例，保持向后兼容
const apiService = new ApiService()

// 同时导出类实例，方便新功能使用
export { apiService, ApiService }
